package com.zhentao.studyim.repository;

import com.zhentao.studyim.entity.Message;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 消息数据访问接口
 */
@Repository
public interface MessageRepository extends JpaRepository<Message, Long> {

    /**
     * 查询两个用户之间的聊天记录
     * 使用JPQL查询语言
     */
    @Query("SELECT m FROM Message m WHERE " +
            "(m.fromUserId = :userId1 AND m.toUserId = :userId2) OR " +
            "(m.fromUserId = :userId2 AND m.toUserId = :userId1) " +
            "ORDER BY m.sendTime ASC")
    List<Message> findChatHistory(@Param("userId1") Long userId1,
                                  @Param("userId2") Long userId2);

    /**
     * 查询发送给指定用户的消息
     */
    List<Message> findByToUserIdOrderBySendTimeDesc(Long toUserId);
}